import copy
import os.path
import pathlib

import pytest
import yaml

from apirunner.api_execute import execute
from apirunner.sessions import Session, CaseInfos


def _yaml_convert_dict(file):
    """
    将 yaml 文件转化为 dict 对象
    :param file: 文件名
    :return: None
    """
    with open(file, encoding='utf-8') as f:
        case_info = yaml.full_load(f)

    # 读取 ddts 节点，生成多组测试用例
    ddts = case_info.get('ddts', [])

    if len(ddts) > 0:
        case_info.pop('ddts')

    if len(ddts) == 0:
        CaseInfos.case_infos.append(case_info)
        CaseInfos.ids.append(case_info.get('desc', None))
    else:
        for ddt in ddts:
            new_case = copy.deepcopy(case_info)
            context = new_case.get('context', {})
            ddt.update(context)
            new_case.update(dict(context=ddt))
            CaseInfos.case_infos.append(new_case)
            desc = ddt.get('desc', None)
            CaseInfos.ids.append(desc)


def pytest_addoption(parser):
    group = parser.getgroup('load_yaml')
    group.addoption(
        '--load',
        action='store',
        dest='dest_load',
        default='.',
        help='加载某个路径下的所有符合命名规范的 yaml 文件测试用例'
    )

    parser.addini('Load', 'Dummy pytest.ini setting')


def pytest_configure(config):
    path = config.option.dest_load

    if pathlib.Path(path).is_file():
        if path.endswith('.yaml'):
            _yaml_convert_dict(path)
        else:
            pytest.exit(f'{path}不是 yaml 格式文件')

    else:
        files = [p for p in pathlib.Path(path).rglob('test*.yaml')]
        if files:
            for file in files:
                _yaml_convert_dict(file)
        else:
            pytest.exit('当前目录未检测到任何测试套件')


@pytest.fixture(scope='session')
def session_context(pytestconfig):
    """返回登录的 cookies 或 token，是会话级别，账号下一次再次登录 cookies 或 token 会失效"""
    context = dict()
    path = pytestconfig.option.dest_load

    if pathlib.Path(path).is_file():
        return context
    else:
        login_yaml = path + '/login.yaml'
        if os.path.exists(login_yaml):
            with open(login_yaml, encoding='utf-8') as f:
                login_dict = yaml.full_load(f)

            execute(login_dict)

            if getattr(Session, 'cookies', None):
                context.update(getattr(Session, 'cookies'))
            if getattr(Session, 'token', None):
                context.update(getattr(Session, 'token'))
            return context
        else:
            return context
